package cn.xf.redis.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class TokenUtils {

    @Autowired
    private RedisUtil redisUtil;

    private Long tokenTimeout = 300L;

    public String createToken(String prefix
            , String value) {
        return createToken(prefix, value, tokenTimeout);
    }

    /**
     * 前缀
     *
     * @param prefix
     * @param value
     * @return
     */
    public String createToken(String prefix
            , String value, Long timeOut) {

        return createToken(prefix, value, timeOut, TimeUnit.MINUTES);
    }

    public String createToken(String prefix, String value, Long timeout, TimeUnit timeUnit) {

        //1.生成我们的令牌
        String token = prefix + ":" + UUID.randomUUID().toString().replace("-", "");
        // 2.将该token存入到Redis中
        redisUtil.set(token, value, timeout, timeUnit);
        return token;
    }

    public Object getTokenValue(String token) {
        return redisUtil.get(token);
    }

    public void del(String formerToken) {

        redisUtil.delKey(formerToken);
    }

    public List<String> getListToken(String keyPrefix, Long tokenQuantity) {
        List<String> listToken = new ArrayList<>();
        for (int i = 0; i < tokenQuantity; i++) {
            String token = keyPrefix + UUID.randomUUID().toString().replace("-", "");
            listToken.add(token);
        }
        return listToken;

    }

    public String getListKeyToken(String key) {
        Object value = redisUtil.getTotalRedisTemplate().opsForList().leftPop(key);
        return value != null ? value.toString() : null;
    }

    public void createListToken(String keyPrefix, String redisKey, Long tokenQuantity) {

        List<String> listToken = getListToken(keyPrefix, tokenQuantity);
        redisUtil.setList(redisKey, listToken);
    }
}
